package com.ly.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

public class MyJsonUtil {
	private static ObjectMapper mapper = new ObjectMapper() {{
		disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
		registerModule(new JavaTimeModule());
	}};

	private MyJsonUtil() {
	}

	public static String obj2String(Object object) {
		String s = null;
		try {
			s = mapper.writeValueAsString(object);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return s;
	}

	public static <T> T string2Obj(String s) {
		T t = null;
		try {
			t = mapper.readValue(s, new TypeReference<T>() {
			});
		} catch (IOException e) {
			e.printStackTrace();
		}
		return t;
	}

	public static <T> T obj2Obj(Object obj) {
		try {
			return mapper.convertValue(obj, new TypeReference<T>() {
			});
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static <T> T obj2Obj(Object obj, TypeReference<T> typeReference) {
		try {
			return mapper.convertValue(obj, typeReference);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static <T> T obj2Obj(Object obj, Class<T> tClass) {
		try {
			return mapper.convertValue(obj, tClass);
		} catch (IllegalArgumentException e) {
			return null;
		}
	}

	public static <T> T string2Obj(String s, Class<T> clazz) {
		try {
			return mapper.readValue(s, clazz);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static <T> T string2Obj(String s, TypeReference<T> typeReference) {
		try {
			return mapper.readValue(s, typeReference);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static <T> List<String> list2String(List<T> list) {
		return list.parallelStream()
				   .map(MyJsonUtil::obj2String)
				   .collect(Collectors.toList());
	}

	public static <T> List<T> string2List(List<String> list, TypeReference<T> typeReference) {
		return list.parallelStream()
				   .map(l -> string2Obj(l, typeReference))
				   .collect(Collectors.toList());
	}

	public static <T> List<T> string2List(List<String> list, Class<T> tClass) {
		return list.parallelStream()
				   .map(l -> string2Obj(l, tClass))
				   .collect(Collectors.toList());
	}

	public static <T> List<T> string2List(List<String> list) {
		return list.parallelStream()
				   .map(MyJsonUtil::<T>string2Obj)
				   .collect(Collectors.toList());
	}
}

